#include "hf_iic_tmp102.h"
#include "hf_hal_iic.h"  // 底层I2C HAL

static int8_t tmp102_write_reg(uint8_t reg_addr, uint16_t value)
{
    uint8_t data[2] = {(value >> 8) & 0xFF, value & 0xFF};
    return hf_iic_write_reg(TMP102_DEFAULT_ADDR, reg_addr, data, 2);
}

static int8_t tmp102_read_reg(uint8_t reg_addr, uint16_t *value)
{
    uint8_t data[2];
    int8_t status = hf_iic_read_reg(TMP102_DEFAULT_ADDR, reg_addr, data, 2);
    if (status == I2C_OK) {
        *value = (data[0] << 8) | data[1];
    }
    return status;
}

static int8_t tmp102_open(struct hf_device *dev)
{
    // 验证设备 (读配置寄存器)
    uint16_t config;
    int8_t status = tmp102_read_reg(TMP102_REG_CONFIG, &config);
    if (status != I2C_OK) return status;

    // 默认配置 (连续转换模式)
    return I2C_OK;
}

static int8_t tmp102_close(struct hf_device *dev)
{
    // 进入关断模式
    return tmp102_write_reg(TMP102_REG_CONFIG, 0x0100);  // SD位设1
}

static int8_t tmp102_read(struct hf_device *dev, uint8_t *p_data, size_t size)
{
    if (size < 2) return I2C_ERROR;

    return hf_iic_read_reg(TMP102_DEFAULT_ADDR, TMP102_REG_TEMP,
                            p_data, 2);
}

static int8_t tmp102_write(struct hf_device *dev, uint8_t *p_data, size_t size)
{
    return I2C_ERROR;  // TMP102不支持通用写
}

static int8_t tmp102_ioctl(struct hf_device *dev, uint32_t cmd, void *arg)
{
    struct hf_dev_tmp102 *tmp102 = (struct hf_dev_tmp102 *)dev;
    int8_t status;

    switch (cmd) {
        case TMP102_CMD_READ_TEMP_RAW: {
            uint16_t raw;
            status = tmp102_read_reg(tmp102->slave_addr, TMP102_REG_TEMP, &raw);
            if (status != I2C_OK) return status;
            *(int16_t *)arg = (int16_t)(raw >> 4);  // 12位分辨率, 右移4位
            break;
        }
        case TMP102_CMD_READ_TEMP_C: {
            uint16_t raw;
            status = tmp102_read_reg(tmp102->slave_addr, TMP102_REG_TEMP, &raw);
            if (status != I2C_OK) return status;
            int16_t temp_raw = (int16_t)(raw >> 4);
            *(float *)arg = temp_raw * 0.0625f;  // 转换为摄氏度
            break;
        }
        case TMP102_CMD_SET_CONFIG: {
            uint16_t config = *(uint16_t *)arg;
            status = tmp102_write_reg(tmp102->slave_addr, TMP102_REG_CONFIG, config);
            break;
        }
        default:
            return I2C_ERROR;
    }
    return I2C_OK;
}

static const struct hf_driver_ops tmp102_ops = {
    .open = tmp102_open,
    .close = tmp102_close,
    .read = tmp102_read,
    .write = tmp102_write,
    .ioctl = tmp102_ioctl
};

int8_t hf_tmp102_init(struct hf_device *dev, const char *name)
{    
    if (dev == NULL) return NULL;

    struct hf_dev_tmp102 *tmp102 = (struct hf_dev_tmp102 *)dev;

    tmp102->slave_addr = TMP102_DEFAULT_ADDR;
    tmp102->dev->ops = &tmp102_ops;
    tmp102->dev->type = E_DEVICE_I2C;
    tmp102->dev->name = name;

    // 注册到抽象层 (priv作为driver_data)
    return (struct hf_device *)dev;
}